// packageFT/guide/application/application.js
const app = getApp()
import WxValidate from '../../../utils/WxValidate'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    saveBtnStatus:false,
    tipstext:'',
    editStatus:false,
    maskStatus: false,
    formData: {
      realname: '',
      mobile: '',
      province_name:'',
      city_name:'',
      district_name:'',
      province_id:'',
      city_id:'',
      district_id:'',
      id_card_front:'',
      id_card_side:'',
      idPortrait: [],
      idEmblem: [],
      // serviceYears: 1,
      // guideLevel: '普通',
      // registerAreaValue: '',
      registerAreaText: '',
      // responsibleArea: [],
      // introduction: '',
      // guideCertificate: [],
    },
    registerAreaValue:'',
    // registerAreaOptions: [],
    // responsibleAreaOptions: [],
    registerAreaShow: false,
    // responsibleAreaShow: false,
    pageType: ''
  },

  /**
   * 数据双向绑定
   * @param {Object} e 
   */
  updateFormData: function(e) {
    const { formdatakey } = e.currentTarget.dataset
    const value = e.detail
    const key = 'formData.' + [formdatakey]
    this.setData({
      [key]: value 
    })
  },

  /**
   * 显示/隐藏弹窗
   * @param {Object} e 
   */
  popupToggle: function(e) {
    if(this.data.editStatus == true){
      return false
    }
    const { text, show } = e.currentTarget.dataset
    this.setData({
      [text]: show
    })
  },

  /**
   * 负责区域选择确认
   * @param {Object} e 
   */
  responsibleAreaFinish: function(e) {
    const {selectedOptions, tabIndex, value } = e.detail
    if (tabIndex == 1) {
      let { responsibleArea } = this.data.formData
      if (responsibleArea.length >= 20) {
        app.tips('最多选择20个')
        return
      }
      const index = responsibleArea.findIndex(item => item.value == value)
      // 已存在
      if (index > -1) {
        app.tips(`已选择【${selectedOptions[1].text}】`)
        return
      }
      responsibleArea.push({
        text: selectedOptions[0].text + '-' + selectedOptions[1].text,
        value
      })
      this.setData({
        'formData.responsibleArea': responsibleArea,
        responsibleAreaShow: false
      })
    }
  },

  /**
   * 删除选中的负责区域
   * @param {Object} e 
   */
  delResponsibleArea: function(e) {
    const { value } = e.target.dataset
    let { responsibleArea } = this.data.formData
    let index = responsibleArea.findIndex(item => item.value == value)
    responsibleArea.splice(index, 1)
    this.setData({
      'formData.responsibleArea': responsibleArea
    })
  },

  /**
   * 注册区域选择确认
   * @param {Object} e 
   */
  registerAreaFinish: function(e) {
    console.log(e)
    const { selectedOptions, value } = e.detail;
    selectedOptions.forEach((item,index)=>{
      if(index == 0){
        this.setData({
          'formData.province_name': item.text
        })
        this.setData({
          'formData.province_id': item.value
        })
      }
      if(index == 1){
        this.setData({
          'formData.city_name': item.text
        })
        this.setData({
          'formData.city_id': item.value
        })
      }
      if(index == 2){
        this.setData({
          'formData.district_name': item.text
        })
        this.setData({
          'formData.district_id': item.value
        })
      }
    })
    const fieldValue = selectedOptions
        .map((option) => option.text || option.name)
        .join('/');
    this.setData({
      'formData.registerAreaText': fieldValue,
      'registerAreaValue': value,
      registerAreaShow: false
    })
  },
  getApplyEditStatus(){
    const _this = this
    let urlStr = app.getNetAddresss("plugin.talent.frontend.talent.validate-edit-apply");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: '',
      success: function (resdata) {
        var res = resdata.data;
        console.log(res)
        if(res.data.status == 1){
          _this.setData({
            maskStatus:true,
            tipstext:'资料修改审核中'
          })
        }
        // _this.setData({
        //   formData:_this.data.formData,
        //   registerAreaValue:_this.data.registerAreaValue
        // })
      },
      fail: function (res) {
        clickTap = 0;
      }
    });
  },
  /**
   * 编辑达人信息
   */
  editApplyforStatus(){
    const _this = this
    let urlStr = app.getNetAddresss("plugin.talent.frontend.talent.normal");
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: this.data.formData,
      success: function (resdata) {
        var res = resdata.data.msg;
        _this.data.formData.realname = res.realname
        _this.data.formData.mobile = res.mobile
        let addressStr = ''
        let addressID = ''
        if(res.province_name){
          addressStr+=res.province_name
          addressID = res.province_id
        }
        if(res.city_name){
          addressStr+='/'+res.city_name
          addressID = res.city_id
        }
        if(res.district_name){
          addressStr+='/'+res.district_name
          addressID = res.district_id
        }
        console.log(addressID,'--------------addressID')
        _this.data.formData.registerAreaText = addressStr
        _this.data.formData.province_name = res.province_name
        _this.data.formData.province_id = res.province_id
        _this.data.formData.city_name = res.city_name
        _this.data.formData.city_id = res.city_id
        _this.data.formData.district_name = res.district_name
        _this.data.formData.district_id = res.district_id
        _this.data.registerAreaValue = addressID
        _this.data.formData.profiles = res.profiles
        _this.data.formData.idPortrait.push({'url':res.id_card_front})
        _this.data.formData.id_card_front = res.id_card_front
        _this.data.formData.idEmblem.push({'url':res.id_card_side})
        _this.data.formData.id_card_side = res.id_card_side
        console.log(_this.data.formData,'----------_this.data.formData')
        _this.setData({
          formData:_this.data.formData,
          registerAreaValue:_this.data.registerAreaValue
        })
      },
      fail: function (res) {
        clickTap = 0;
      }
    });
  },
  /**
   * 查询达人申请状态
   */
  queryApplyforStatus(){
    const _this = this
    let urlStr = app.getNetAddresss("plugin.talent.frontend.apply.index");
    app._getNetWork({
      url: urlStr,
      showToastIn: false,
      data: this.data.formData,
      success: function (resdata) {
        var res = resdata.data;
        if(res.data.status !== 1){
          _this.setData({
            maskStatus: true,
            tipstext:'您的达人申请正在审核中'
          })
        }
      },
      fail: function (res) {
        clickTap = 0;
      }
    });
  },
  backCenter(){
    // wx.navigateTo({
    //   url: "/packageG/member_v2/member_v2"
    // });
    wx.navigateBack({
      delta:1
    })
  },
  /**
   * 提交申请
   */
  submitForm: function() {
    if(this.data.editStatus){
      this.setData({
        editStatus: false,
        saveBtnStatus:true
      })
      wx.showToast({
        icon: 'none',
        title: '您现在可以编辑修改您的信息了',
        duration: 1500
      });
      wx.setNavigationBarTitle({
        title: '编辑资料',
      })
      return false
    }
    if (!this.WxValidate.checkForm(this.data.formData)) {
      const error = this.WxValidate.errorList[0]
      app.tips(error.msg)
      return
    }
    let ajaxUrl = ''
    if(this.data.pageType == 'edit'){
      ajaxUrl = "plugin.talent.frontend.talent.editApply"
    } else {
      ajaxUrl = "plugin.talent.frontend.apply.apply"
    }
    console.log(ajaxUrl,'-------ajaxUrl')
    let urlStr = app.getNetAddresss(ajaxUrl);
    app._postNetWork({
      url: urlStr,
      showToastIn: false,
      data: this.data.formData,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result === 1) {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
          setTimeout(function(){
            // wx.navigateTo({
            //   url: "/packageG/member_v2/member_v2"
            // });
            const { tmplIds } = app.data
            wx.requestSubscribeMessage({
              tmplIds: tmplIds[1],
              complete: function() {
                wx.navigateBack({
                  delta:1
                })
              }
            })
          },1500)
        } else {
          wx.showToast({
            icon: 'none',
            title: res.msg,
            duration: 1500
          });
        }
      },
      fail: function (res) {
        clickTap = 0;
      }
    });
  },

  /**
   * 图片选中上传(多图)
   * @param {Object} e 
   */
  afterRead: function(e) {
    const { file = [] } = e.detail
    let promiseArray = []
    const uploaderUrl = app.getNetAddresss(app.data.uploaderPicUrl)
    wx.showLoading({
      title: '上传中',
    })
    file.forEach(item => {
      promiseArray.push(new Promise((resolve, reject) => {
        wx.uploadFile({
          filePath: item.url,
          name: 'file',
          url: uploaderUrl,
          success: function(res) {
            resolve(res)
          },
          fail: function(err) {
            reject(err)
          }
        })
      }))
    })
    Promise.all(promiseArray).then(resArray => {
      wx.hideLoading()
      const addUrlArray = resArray.map(item => {
        const resData = JSON.parse(item.data)
        return {url: resData.data.img_url}
      })
      const { formData } = this.data
      const { field } = e.currentTarget.dataset
      const currentImgUrls = [...this.data.formData[field], ...addUrlArray]
      formData[field] = currentImgUrls
      if(field == 'idPortrait'){
        this.setData({ 
          'formData.id_card_front':addUrlArray[0].url
        })
      }
      if(field == 'idEmblem'){
        this.setData({ 
          'formData.id_card_side':addUrlArray[0].url
        })
      }
      this.setData({ formData })
    }).catch(err => {
      wx.hideLoading()
    })
  },

  /**
   * 删除已上传的图片
   * @param {Object} e 
   */
  deleteFile: function(e) {
    const { index } = e.detail
    const { field } = e.currentTarget.dataset
    let currentData = this.data.formData[field]
    const key = `formData.${field}`
    currentData.splice(index, 1)
    this.setData({
      [key]: currentData
    })
  },

  /**
   * 获取省市列表(出行城市)
   */
  getAddress: function() {
    wx.showLoading({
      title: '加载中...',
    })
    const _this = this
    let urlStr = app.getNetAddresss("member.member-address.address");
    app._postNetWork({
      url: urlStr,
      success: function(res) {
        const resData = res.data
        if (resData.result == 1) {
          const thirdLevelRegion = resData.data.province.map(item => {
            const child = resData.data.city.filter(item1 => item1.parentid == item.id).map(item1 => {
              const child2 = resData.data.district.filter(item2 => item2.parentid == item1.id).map(item2 => {
                return {
                  text: item2.areaname,
                  value: item2.id + ''
                }
              })
              return {
                text: item1.areaname,
                value: item1.id + '',
                children: child2
              }
            })
            return {
              text: item.areaname,
              value: item.id + '',
              children: child
            }
          })
          const secondaryRegion = resData.data.province.map(item => {
            const child = resData.data.city.filter(item1 => item1.parentid == item.id).map(item1 => {
              return {
                text: item1.areaname,
                value: item1.id + ''
              }
            })
            return {
              text: item.areaname,
              value: item.id + '',
              children: child
            }
          })
          _this.setData({ 
            registerAreaOptions: thirdLevelRegion,
            responsibleAreaOptions: secondaryRegion
          })
        } else {
          app.tips(resData.msg)
        }
      },
      complete: function() {
        wx.hideLoading()
      }
    })
  },

  /**
   * 表单验证
   */
  initValidate: function() {
    const rules = {
      realname: {
        required: true
      },
      mobile: {
        required: true,
        tel: true
      },
      registerAreaText: {
        required: true
      },
      // responsibleArea: {
      //   isEmptyArray: true
      // },
      profiles: {
        required: true
      },
      // guideCertificate: {
      //   isEmptyArray: true
      // },
      idPortrait: {
        isEmptyArray: true
      },
      idEmblem: {
        isEmptyArray: true
      }
    }
    const message = {
      realname: {
        required: '请输入姓名'
      },
      mobile: {
        required: '请输入手机号',
        tel: '请输入正确的手机号码'
      },
      registerAreaText: {
        required: '请选择注册区域'
      },
      // responsibleArea: {
      //   isEmptyArray: '请选择负责区域'
      // },
      profiles: {
        required: '请填写个人简介'
      },
      // guideCertificate: {
      //   isEmptyArray: '请上传导游证件'
      // },
      idPortrait: {
        isEmptyArray: '请上传身份证人像面'
      },
      idEmblem: {
        isEmptyArray: '请上传身份证国徽面'
      }
    }
    this.WxValidate = new WxValidate(rules, message)
    this.WxValidate.addMethod('isEmptyArray', (value) => {
      return value.length > 0
    })
  },

  /**
   * 根据参数页面类型设置不同显示
   * @param {Object} options 
   */
  setPageInfo: function(options) {
    this.setData({
      pageType: options?.pageType || ''
    })
    const { pageType } = options
    if (pageType && pageType == 'add') {
      wx.setNavigationBarTitle({
        title: '达人申请',
      })
      this.queryApplyforStatus()
    } else if (pageType && pageType == 'edit') {
      this.setData({
        editStatus: true
      })
      wx.setNavigationBarTitle({
        title: '我的资料',
      })
      this.getApplyEditStatus()
      this.editApplyforStatus()
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.initValidate()
    this.getAddress()
    this.setPageInfo(options)
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})